<script lang="ts" setup>
  import { onMounted, ref, watch } from 'vue';
  import { useSalesStore } from '@/store';

  const list = ref<any>([]);
  const salesStore = useSalesStore();
  const searchForm = ref<any>({});
  const emit = defineEmits(['select']);
  const modalVisible = ref(false);
  const model = defineModel();
  const label = ref('');

  async function fetchList() {
    list.value = await salesStore.getCompanies(searchForm.value);
  }

  watch(
    () => model.value,
    (val) => {
      if (val) {
        label.value = list.value.find((item: any) => item.id === model.value)?.name;
      } else {
        label.value = '';
      }
    }
  );

  onMounted(async () => {
    await fetchList();
  });

  function handleSelect(record: any) {
    model.value = record.id;
    label.value = record.name;
    modalVisible.value = false;
  }
</script>

<template>
  <div>
    <a-space>
      <a-input placeholder="请选择公司" v-model="label" />
      <a-button type="primary" @click="modalVisible = true">选择</a-button>
    </a-space>
    <a-modal :visible="modalVisible" title="选择公司" @cancel="modalVisible = false" :footer="false">
      <a-table :data="list">
        <template #columns>
          <a-table-column title="编号" :width="80" data-index="id"></a-table-column>
          <a-table-column title="姓名" data-index="name"></a-table-column>
          <a-table-column title="操作" :width="120">
            <template #cell="{ record }">
              <a-space>
                <a-button type="primary" @click="handleSelect(record)" size="small">选择</a-button>
              </a-space>
            </template>
          </a-table-column>
        </template>
      </a-table>
    </a-modal>
  </div>
</template>
